package com.bestseller.proxy;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

public class ConllectionProxy {
	public static void main(String[] args) throws Exception{
		Class proxyClass = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
		Constructor[] constructors = proxyClass.getConstructors();
		System.out.println("---------------constructor list-----------");
		for(Constructor constructor:constructors){
			StringBuilder sb=new StringBuilder();
			sb.append(constructor.getName());
			sb.append("(");
			Class[] parameterTypes = constructor.getParameterTypes();
			for(Class clazz:parameterTypes){
				sb.append(clazz.getSimpleName());
				sb.append(",");
			}
			sb.append(")");
			if(parameterTypes.length!=0&&parameterTypes!=null){
				sb.deleteCharAt(sb.lastIndexOf(","));
			}
			System.out.println(sb.toString());
		}
		
		/*System.out.println("---------------method list-----------");
		MethodList(proxyClass);*/
		
		System.out.println("------------instance of object------");
		Constructor constructor=proxyClass.getConstructor(InvocationHandler.class);
		Collection collection=(Collection) constructor.newInstance(new InvocationHandler(){
			
			ArrayList al=new ArrayList();
			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				// TODO Auto-generated method stub
				if(method.getName().equals("add")){
					Object result=method.invoke(al, args);
					return result;
				}if(method.getName().equals("size")){
					return al.size();
				}
				
				
				return null;
			}
			
		});
		System.out.println(collection);
		collection.add("xgx");
		collection.add("cfl");
		System.out.println(collection);
		System.out.println(collection.size());
		
		
		Map map=(Map) Proxy.newProxyInstance(Map.class.getClassLoader(), 
				new Class[]{Map.class}, 
				new InvocationHandler(){

					@Override
					public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
						return null;
					}
			
		});
		
		
	}


	private static void MethodList(Class proxyClass) {
		Method[] methods = proxyClass.getMethods();
		for(Method method:methods){
			StringBuilder sb=new StringBuilder();
			sb.append(method.getName());
			sb.append("(");
			Class[] parameterTypes = method.getParameterTypes();
			for(Class clazz:parameterTypes){
				sb.append(clazz.getSimpleName());
				sb.append(",");
			}
			sb.append(")");
			if(parameterTypes.length!=0&&parameterTypes!=null){
				sb.deleteCharAt(sb.lastIndexOf(","));
			}
			System.out.println(sb.toString());
		}
	}
}
